package main.users;

import main.SQL.MsSQLConnect;
import main.components.GradientPanel;

import javax.swing.*;
import java.awt.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class UsersDialog {
    private JTable usersTable;
    private UsersTableModel usersTableModel;
    private Connection connSQL;

    public UsersDialog() {
        initComponenets();
    }

    private void initComponenets() {
        JDialog dlg = new JDialog();
        dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dlg.setLayout(new GridBagLayout());
        dlg.setTitle("Factage Users");
        dlg.setResizable(true);
        dlg.setType(java.awt.Window.Type.UTILITY);
        dlg.setModal(true);

        //region Инициализация шапки
        GradientPanel headerPanel = new GradientPanel(new GridBagLayout(), new Color(252, 141, 234), new Color(178, 99, 164));
        JLabel headerLabel = new JLabel("Пользователи системы Factage");
        headerLabel.setFont(new Font("Segoe UI", 0, 18));
        headerLabel.setForeground(Color.WHITE);
        dlg.add(headerPanel, new GridBagConstraints(0, 0, 3, 1, 0.1, 0.1, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        headerPanel.add(headerLabel, new GridBagConstraints(0, 0, 1, 1, 0.5, 0, GridBagConstraints.WEST, GridBagConstraints.WEST, new Insets(30, 56, 7, 56), 0, 0));
        //endregion

        JToolBar toolBar = new JToolBar();
        toolBar.setRollover(true);
        toolBar.setFloatable(false);
        toolBar.setBackground(new Color(130, 130, 130));

        JButton addUserButton = new JButton("Добавить пользователя");
        addUserButton.setForeground(new Color(240, 240, 240));
        addUserButton.setBackground(new Color(130, 130, 130));
        addUserButton.setMargin(new Insets(4, 5, 4, 5));
        addUserButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                new AddUserDialog(usersTableModel);
                usersTableModel.getDataFromSQL();
                usersTable.revalidate();
            }
        });
        toolBar.add(addUserButton);
        dlg.add(toolBar, new GridBagConstraints(0, 1, 3, 1, 0.1, 0.1, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));

        JButton deleteUserButton = new JButton("Удалить пользователя");
        deleteUserButton.setForeground(new Color(240, 240, 240));
        deleteUserButton.setBackground(new Color(130, 130, 130));
        deleteUserButton.setMargin(new Insets(4, 5, 4, 5));
        deleteUserButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (usersTable.getSelectedRowCount() > 0) {
                    deleteUser();
                }
            }
        });
        toolBar.add(deleteUserButton);

        JButton resetUserPasswordButton = new JButton("Сбросить пароль");
        resetUserPasswordButton.setForeground(new Color(240, 240, 240));
        resetUserPasswordButton.setBackground(new Color(130, 130, 130));
        resetUserPasswordButton.setMargin(new Insets(4, 5, 4, 5));
        resetUserPasswordButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (usersTable.getSelectedRowCount() > 0) {
                    resetUserPassword();
                }
            }
        });
        toolBar.add(resetUserPasswordButton);

        usersTable = new JTable();
        usersTableModel = new UsersTableModel();
        usersTable.setModel(usersTableModel);
        initUsersTable();

        JScrollPane jScrollPane1 = new JScrollPane();
        jScrollPane1.setViewportView(usersTable);

        dlg.add(jScrollPane1, new GridBagConstraints(0, 2, 3, 1, 100, 100, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(18, 56, 30, 56), 0, 0));

        dlg.pack();

        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        dlg.setLocation(screensize.width / 2 - dlg.getWidth() / 2, screensize.height / 2 - dlg.getHeight() / 2);

        dlg.setVisible(true);

    }

    private void initUsersTable() {
        usersTable.setShowGrid(true);
        usersTable.setRowHeight(20);
        usersTable.setGridColor(new Color(219, 219, 219));

        if (usersTable.getColumnModel().getColumnCount() > 0) {
            usersTable.getColumnModel().getColumn(0).setMinWidth(10);
            usersTable.getColumnModel().getColumn(0).setPreferredWidth(50);
            usersTable.getColumnModel().getColumn(0).setMaxWidth(50);
            usersTable.getColumnModel().getColumn(3).setMinWidth(70);
            usersTable.getColumnModel().getColumn(3).setPreferredWidth(130);
            usersTable.getColumnModel().getColumn(3).setMaxWidth(170);

            JComboBox comboBox = new JComboBox(usersTableModel.getUserRoles().values().toArray());
            usersTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(comboBox));
            usersTable.getColumnModel().getColumn(3).getCellEditor().addCellEditorListener(new CellEditorListener() {
                @Override
                public void editingStopped(ChangeEvent changeEvent) {
                    updateUser(usersTable.getSelectedRow());
                }

                @Override
                public void editingCanceled(ChangeEvent changeEvent) {

                }
            });

            TableCellEditor tableCellEditor = usersTable.getDefaultEditor(String.class);
            usersTable.getColumnModel().getColumn(2).setCellEditor(tableCellEditor);
            tableCellEditor.addCellEditorListener(new CellEditorListener() {
                @Override
                public void editingStopped(ChangeEvent changeEvent) {
                    updateUser(usersTable.getSelectedRow());
                }

                @Override
                public void editingCanceled(ChangeEvent changeEvent) {

                }
            });


        }
    }

    private void updateUser(int row) {
        try {
            connSQL = MsSQLConnect.ConnectDB("Factage");

            Statement stat = connSQL.createStatement();
            stat.executeUpdate("UPDATE users SET [name] = '" + usersTableModel.getValueAt(row, 2) + "', [role_id] = (select id from user_roles where name = '" + usersTableModel.getValueAt(row, 3) + "') WHERE [login] = '" + usersTableModel.getValueAt(row, 1) + "' ");
            stat.close();

            connSQL.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        usersTableModel.getDataFromSQL();
        usersTable.revalidate();
    }

    private void deleteUser() {

        try {
            connSQL = MsSQLConnect.ConnectDB("Factage");

            Statement stat = connSQL.createStatement();
            for (int i : usersTable.getSelectedRows()) {
                stat.addBatch("delete from users where login = '"+usersTableModel.getValueAt(i, 1)+"'");
            }

            stat.executeBatch();
            stat.close();

            connSQL.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        usersTableModel.getDataFromSQL();
        usersTable.revalidate();
    }

    private void resetUserPassword() {
        try {
            connSQL = MsSQLConnect.ConnectDB("Factage");

            Statement stat = connSQL.createStatement();
            for (int i : usersTable.getSelectedRows()) {
                stat.addBatch("UPDATE users SET [password] = '"+FactageUser.md5(usersTableModel.getValueAt(i, 1).toString())+"' WHERE [login] = '"+usersTableModel.getValueAt(i, 1)+"' ");
            }

            stat.executeBatch();
            stat.close();

            connSQL.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        usersTableModel.getDataFromSQL();
        usersTable.revalidate();
    }

}
